package com.xingshentech.ugv.operate.module.login;

import android.content.Intent;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdate;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.CoordinateConverter;
import com.amap.api.maps.MapView;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.gson.JsonArray;
import com.xingshentech.ugv.operate.R;
import com.xingshentech.ugv.operate.base.ApplicationShare;
import com.xingshentech.ugv.operate.base.BaseActivity;
import com.xingshentech.ugv.operate.module.adapter.CarListAdapter;
import com.xingshentech.ugv.operate.module.adapter.CurrentStationNumAdapter;
import com.xingshentech.ugv.operate.module.bean2.AllVehiclePositionBean;
import com.xingshentech.ugv.operate.module.bean2.BaseResponseCenter;
import com.xingshentech.ugv.operate.module.bean2.CarListBean;
import com.xingshentech.ugv.operate.module.bean2.CurrentStationInfo;
import com.xingshentech.ugv.operate.module.bean2.PageResult;
import com.xingshentech.ugv.operate.module.constant.Constants;
import com.xingshentech.ugv.operate.module.httpdata.MockApi;
import com.xingshentech.ugv.operate.module.listener.OnMultiClickListener;
import com.xingshentech.ugv.operate.module.main.MainActivity;
import com.xingshentech.ugv.operate.module.utils.ToastUtil;
import com.xingshentech.ugv.operate.widget.TopBar;
import com.xstech.library.app.AppManager;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;

public class CarListActivity extends BaseActivity {
    @BindView(R.id.topBar)
    TopBar topBar;
    @BindView(R.id.mapView)
    MapView mapView;
    @BindView(R.id.stationRV)
    RecyclerView stationRV;
    @BindView(R.id.carRV)
    RecyclerView carRV;
    @BindView(R.id.et_search)
    EditText et_search;
    @BindView(R.id.et_searchCar)
    EditText et_searchCar;
    public static boolean firstSelec = true;//第一次选择是登陆，之后的都是切换
    String curStationId = "4294450615116890188";
    Map<String, String> map = new HashMap<>();
    AMap aMap;
    private List<CurrentStationInfo> stationList_org = new ArrayList<>();
    private List<CurrentStationInfo> stationList = new ArrayList<>();
    private List<CarListBean> carList_org = new ArrayList<>();
    private List<CarListBean> carList = new ArrayList<>();
    private CarListAdapter mCarAdapter;
    private CurrentStationNumAdapter mStationAdapter;
    String searchName = "";
    String searchCarName = "";
    CoordinateConverter converter;

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_car_list2;
    }

    @Override
    protected void initView(Bundle savedInstanceState) {


        mapView.onCreate(savedInstanceState);   //此方法必须重写
        aMap = mapView.getMap();
        aMap.getUiSettings().setZoomControlsEnabled(false);
        CameraUpdate mCameraUpdate = CameraUpdateFactory.zoomTo(14);
        aMap.animateCamera(mCameraUpdate);
        converter = new CoordinateConverter(CarListActivity.this).from(CoordinateConverter.CoordType.GPS);


        initStation();
        initCar();

        performSearchByAny();

        topBar.setText(Constants.is4gconnect ? "车辆列表(4G)" : "车辆列表(WIFI直连)");
        topBar.addRightBtn(R.mipmap.icon_owner_information, new OnMultiClickListener() {
            @Override
            public void onMultiClick(View v) {
//                showAction();
            }
        });
        isLogin(false);
    }


    @Override
    protected void initData() {
        getStation();
        notifyMonitorSiteInfo();
    }

    private void performSearchByAny() {
        et_search.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                mHandler.removeMessages(1);
                searchName = s.toString();
                mHandler.sendEmptyMessageDelayed(1, 800);
            }
        });
        et_searchCar.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                mHandler.removeMessages(2);
                searchCarName = s.toString();
                mHandler.sendEmptyMessageDelayed(2, 800);
            }
        });
    }

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == 1) getStation();
            if (msg.what == 2) searchCar();
        }
    };

    private void getStation() {

//        JsonObject jsonObject = new JsonObject();
//        jsonObject.addProperty("rotePath", ApiAddress.siteInfoQueryContent);
//        jsonObject.addProperty("requestMethod", "GET");
//        jsonObject.addProperty("apiVersion", "v1");
//        JsonObject requestParam = new JsonObject();
//        requestParam.addProperty("queryContent", searchName);
//        jsonObject.add("requestParam", requestParam);
//        RetrofitUtil.getInstance().initRetrofit()
//                .getSiteInfo(jsonObject)
//                .subscribeOn(Schedulers.io())
//                .observeOn(AndroidSchedulers.mainThread())
//                .map(new JsonResponseFunc<>())
//                .subscribe(new BaseObserverCenter<List<CurrentStationInfo>>(this, getString(R.string.Loading)) {
//                    @Override
//                    public void onNext(List<CurrentStationInfo> currentStationInfos) {
//                        if (currentStationInfos != null && currentStationInfos.size() > 0) {
//                            stationList.clear();
//                            stationList.addAll(currentStationInfos);
//                            stationList_org.clear();
//                            stationList_org.addAll(currentStationInfos);
//                            mStationAdapter.notifyDataSetChanged();
//                            stationList.get(0).setSelect(true);
//                            curStationId = stationList.get(0).getId();
//                            getCarList();
//                        }
//                    }
//                });

        MockApi mockApi = new MockApi(this);
        List<CurrentStationInfo> currentStationInfos = mockApi.getMockStationList();

        if (currentStationInfos != null && currentStationInfos.size() > 0) {
            stationList.clear();
            stationList.addAll(currentStationInfos);
            stationList_org.clear();
            stationList_org.addAll(currentStationInfos);
//            mStationAdapter.notifyDataSetChanged();
            stationList.get(0).setSelect(true);
            curStationId = stationList.get(0).getId();
            getCarList();
        }
    }

    public void initStation() {
        stationRV.setLayoutManager(new LinearLayoutManager(this));
        // 绑定数据到 RecyclerView
        mStationAdapter = new CurrentStationNumAdapter(this, stationList);
        stationRV.setAdapter(mStationAdapter);

        mStationAdapter.setOnItemClickListener((position, data) -> {
            curStationId = data.getId();
            getCarList();
        });
    }

    public void initCar() {
        carRV.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
        mCarAdapter = new CarListAdapter(this, carList);
        mCarAdapter.setEmptyView(EmptyView());
        mCarAdapter.setAnimationEnable(true);
        mCarAdapter.setAnimationWithDefault(BaseQuickAdapter.AnimationType.AlphaIn);
        carRV.setAdapter(mCarAdapter);
        mCarAdapter.setOnItemChildClick((view, carListBean) -> {
            switch (view.getId()) {
                case R.id.parent:
                    Intent intent = new Intent(CarListActivity.this, MainActivity.class);
                    Constants.mCarListBean = carListBean;
                    startActivity(intent);
//                    XsLog.getInstance().save("选车切换:" + carListBean.getVehicle().getVehicleName());
                    break;
                case R.id.tv_subscribe:
//                    subscribeCarPush(carListBean.getVehicle().getIdentifyingCode());
                    break;
                case R.id.tv_device_control:
//                    alert("确定唤醒" + carListBean.getVehicle().getVehicleName() + "吗?", "确定", new OnMultiClickListener() {
//                        @Override
//                        public void onMultiClick(View v) {
//                            deviceControl(carListBean);
//                        }
//                    });
                    break;
                case R.id.tv_stop_charge:
//                    alert("确定让" + carListBean.getVehicle().getVehicleName() + "停止充电吗?", "确定", new OnMultiClickListener() {
//                        @Override
//                        public void onMultiClick(View v) {
//                            controlCharge(carListBean, "2");
//                        }
//                    });
                    break;
            }


        });
    }

    private void getCarList() {
//        JsonObject jsonObject = new JsonObject();
//        jsonObject.addProperty("rotePath", ApiAddress.vehicle);
//        jsonObject.addProperty("requestMethod", "GET");
//        jsonObject.addProperty("apiVersion", "v1");
//        JsonObject requestParam = new JsonObject();
//        requestParam.addProperty("id", curStationId);
//        jsonObject.add("requestParam", requestParam);
//        RetrofitUtil.getInstance().initRetrofit()
//                .getVehicle(jsonObject)
//                .subscribeOn(Schedulers.io())
//                .observeOn(AndroidSchedulers.mainThread())
//                .map(new JsonResponseFunc<>())
//                .subscribe(new BaseObserverCenter<PageResult<List<CarListBean>>>(this, false) {
//
//                    @SuppressLint("NewApi")
//                    @Override
//                    public void onNext(PageResult<List<CarListBean>> listPageResult) {
//                          updateCarList(listPageResult);
//                });
        MockApi mockApi = new MockApi(this);
        PageResult<List<CarListBean>> listPageResult = mockApi.getMockCarList();
        updateCarList(listPageResult);

    }

    public void updateCarList(PageResult<List<CarListBean>> listPageResult) {
        if (listPageResult == null || listPageResult.getData() == null) {
            carList.clear();
            carList_org.clear();
            aMap.clear();
            mCarAdapter.notifyDataSetChanged();
            return;
        }

        String totalCount = listPageResult.getTotalCount();
        int i = Integer.parseInt(totalCount);
        if (i > 0) {
            List<CarListBean> data = listPageResult.getData();

//            排序: 在线车辆排在前面
//            Collections.sort(data, (o1, o2) -> {
//                if (o1.getVehicle() != null && o2.getVehicle() != null) {
//                    boolean onLine1 = o1.getVehicle().isOnline();
//                    boolean onLine2 = o2.getVehicle().isOnline();
//
//                    // 如果有搜索关键字，优先匹配搜索内容
//                    if (!searchName.isEmpty() && isLetterDigit(searchName)) {
//                        return o1.getVehicle().getVehicleName().contains(searchName) ? -1 : 1;
//                    }
//                    return Boolean.compare(onLine2, onLine1); // true 为 1，false 为 0，实现在线优先
//                }
//                return 0;
//            });

            // 更新列表数据
            carList_org.clear();
            carList_org.addAll(data);
            searchCar(); // 触发搜索过滤 赋值车辆列表

            // 更新车辆标识映射
            for (CarListBean dataBean : data) {
                if (dataBean.getVehicle() != null && dataBean.getVehicle().getIdentifyingCode() != null) {
                    map.put(dataBean.getVehicle().getIdentifyingCode(), dataBean.getVehicle().getVehicleName());
                }
            }

            // 获取车辆位置
            getCarPosition(data);
        } else {
            carList.clear();
            carList_org.clear();
            aMap.clear();
        }

        // 更新 UI
        mCarAdapter.notifyDataSetChanged();
    }

    public void searchCar() {
        carList.clear();
        if (carList_org != null && carList_org.size() > 0) {
            String name = searchCarName.toLowerCase();
            for (CarListBean carListBean : carList_org) {
                if (carListBean.getVehicle() != null) {
                    String vehicleName = carListBean.getVehicle().getVehicleName().toLowerCase();
                    if (vehicleName.contains(name)) {
                        carList.add(carListBean);
                    }
                }
            }

            mCarAdapter.notifyDataSetChanged();
        }
    }

    public void isLogin(boolean isOnNewIntent) {
        String isNew = isOnNewIntent ? "onNewIntent" : "oncreate";
//        if (Constants.mUser == null) {
//            XsLog.getInstance().save("判断是否登陆:可能是通过推送通知点击跳转,mUser为空-" + isNew);
//            LogUtils.e("onNewIntent", "mUser是null-" + isNew);
//            Intent intent = new Intent(this, LoginActivity.class);
//            startActivity(intent);
//            finish();
//        } else {
//            XsLog.getInstance().save("判断是否登陆:可能是通过推送通知点击跳转,mUser不为空-" + isNew);
//            LogUtils.e("onNewIntent", "mUser不是null-" + isNew);
//        }
    }

    private void notifyMonitorSiteInfo() {
//        RetrofitUtil.getInstance().initRetrofit()
//                .monitor_siteInfo()
//                .subscribeOn(Schedulers.io())
//                .observeOn(AndroidSchedulers.mainThread())
//                .subscribe(new BaseObserverCenter<BaseResponseCenter<Object>>() {
//                    @Override
//                    public void onNext(BaseResponseCenter<Object> objectBaseResponseCenter) {
//
//                    }
//                });
        MockApi mockApi = new MockApi(this);
        BaseResponseCenter<Object> objectBaseResponseCenter = mockApi.notifyMonitorSiteInfo();
    }

    //command 1-开始充电 2-结束充电
    private void controlCharge(CarListBean carListBean, String command) {
//        JsonObject jsonObject = new JsonObject();
//        JsonObject jsonObject1 = new JsonObject();
//        jsonObject1.addProperty("vehicleCode", carListBean.getVehicle().getIdentifyingCode());
//        jsonObject1.addProperty("deviceCode", "1");
//        jsonObject1.addProperty("command", command);
//        jsonObject.add("deviceControlVO", jsonObject1);
//        CenterRequest centerRequest = new CenterRequest();
//        centerRequest.setRotePath(ApiAddress.stopCharge);
//        centerRequest.setRequestMethod("POST");
//        centerRequest.setRequestParam(jsonObject);
//        centerRequest.setRequestParam(jsonObject);
//        RetrofitUtil.getInstance().initRetrofit()
//                .deviceControl(centerRequest)
//                .subscribeOn(Schedulers.io())
//                .observeOn(AndroidSchedulers.mainThread())
//                .map(new JsonResponseFunc<>())
//                .subscribe(new BaseObserverCenter<Boolean>() {
//                    @Override
//                    public void onNext(Boolean aBoolean) {
//                        if (aBoolean) {
//                            toast("停止充电指令发送成功");
//                        }
//                    }
//                });

        MockApi mockApi = new MockApi(this);
        Boolean aBoolean = mockApi.controlCharge();
        if (aBoolean) {
            toast("停止充电指令发送成功");
        }
    }

    private void deviceControl(CarListBean carListBean) {
//        JsonObject jsonObject = new JsonObject();
//        JsonObject jsonObject1 = new JsonObject();
//        jsonObject1.addProperty("vehicleCode", carListBean.getVehicle().getIdentifyingCode());
//        jsonObject1.addProperty("deviceCode", "1");
//        jsonObject1.addProperty("command", "2");
//        jsonObject.add("deviceControlVO", jsonObject1);
//        CenterRequest centerRequest = new CenterRequest();
//        centerRequest.setRotePath(ApiAddress.deviceControl);
//        centerRequest.setRequestMethod("POST");
//        centerRequest.setRequestParam(jsonObject);
//        RetrofitUtil.getInstance().initRetrofit()
//                .deviceControl(centerRequest)
//                .subscribeOn(Schedulers.io())
//                .observeOn(AndroidSchedulers.mainThread())
//                .map(new JsonResponseFunc<>())
//                .subscribe(new BaseObserverCenter<Boolean>() {
//                    @Override
//                    public void onNext(Boolean aBoolean) {
//                        if (aBoolean) {
        toast("唤醒指令发送成功");
//                        }
//                    }
//                });
    }

    public static void strV(String string) {

    }

    public boolean isLetterDigit(String str) {
        boolean isDigit = false;//定义一个boolean值，用来表示是否包含数字
        boolean isLetter = false;//定义一个boolean值，用来表示是否包含字母
        for (int i = 0; i < str.length(); i++) {
            if (Character.isDigit(str.charAt(i))) {   //用char包装类中的判断数字的方法判断每一个字符
                isDigit = true;
            }
            if (Character.isLetter(str.charAt(i))) {  //用char包装类中的判断字母的方法判断每一个字符
                isLetter = true;
            }
        }
        String regex = "^[a-zA-Z0-9]+$";
        boolean isRight = (isDigit || isLetter) && str.matches(regex);
        return isRight;

    }

    //获取车辆的坐标
    public void getCarPosition(List<CarListBean> dataBeanList) {
        JsonArray jsonArray = new JsonArray();
        for (CarListBean dataBean : dataBeanList) {
            if (dataBean.getVehicle() != null && dataBean.getVehicle().getIdentifyingCode() != null) {
                jsonArray.add(dataBean.getVehicle().getIdentifyingCode());
            }
        }
//        JsonObject jsonObject = new JsonObject();
//        jsonObject.addProperty("rotePath", ApiAddress.getAllVehiclePosition);
//        jsonObject.addProperty("requestMethod", "POST");
//        jsonObject.addProperty("apiVersion", "v1");
//        JsonObject requestParam = new JsonObject();
//        requestParam.add("vehicleCodes", jsonArray);
//        jsonObject.add("requestParam", requestParam);
//        RetrofitUtil.getInstance().initRetrofit()
//                    .getAllVehiclePosition(jsonObject)
//                .subscribeOn(Schedulers.io())
//                .observeOn(AndroidSchedulers.mainThread())
//                .map(new JsonResponseFunc<>())
//                .subscribe(new BaseObserverCenter<List<AllVehiclePositionBean>>() {
//                    @Override
//                    public void onNext(List<AllVehiclePositionBean> allVehiclePositionBeans) {
//                        aMap.clear();
//                        if (allVehiclePositionBeans != null) {
//
//                            for (AllVehiclePositionBean bean : allVehiclePositionBeans) {
//                                LatLng latLng1 = new LatLng(bean.getStatusData().getLatitude(), bean.getStatusData().getLongitude());
//                                converter.coord(latLng1);
//                                //绘制marker
//                                Marker marker = aMap.addMarker(new MarkerOptions()
//                                        .position(converter.convert())
//                                        .icon(BitmapDescriptorFactory.fromBitmap(BitmapFactory
//                                                .decodeResource(getResources(), R.mipmap.xs_icon_location)))
//                                        .draggable(true));
//                                String title = map.get(bean.getVehicleCode());
//                                marker.setTitle(title + "");
//                                marker.showInfoWindow();
//                                aMap.animateCamera(CameraUpdateFactory.changeLatLng(converter.convert()));
////                                latLng = new LatLng(bean.getStatusData().getLatitude(), bean.getStatusData().getLongitude());
//                            }
////                            if (latLng != null) {
////                                aMap.animateCamera(CameraUpdateFactory.changeLatLng(latLng));
////                            }
//
//                        }
//                    }
//
//                });

        MockApi mockApi = new MockApi(this);
        List<AllVehiclePositionBean> allVehiclePositionBeans = mockApi.getVehiclePosition();
        aMap.clear();
        if (allVehiclePositionBeans != null) {
            for (AllVehiclePositionBean bean : allVehiclePositionBeans) {
                LatLng latLng1 = new LatLng(bean.getStatusData().getLatitude(), bean.getStatusData().getLongitude());
                converter.coord(latLng1);
                //绘制marker
                Marker marker = aMap.addMarker(new MarkerOptions()
                        .position(converter.convert())
                        .icon(BitmapDescriptorFactory.fromBitmap(BitmapFactory
                                .decodeResource(getResources(), R.mipmap.xs_icon_location)))
                        .draggable(true));
                String title = map.get(bean.getVehicleCode());
                marker.setTitle(title + "");
                marker.showInfoWindow();
                aMap.animateCamera(CameraUpdateFactory.changeLatLng(converter.convert()));
            }
        }


    }

    private Long backTime = 0L;

    @Override
    public void onBackPressed() {
        if (System.currentTimeMillis() > 3000 + backTime) {
            backTime = System.currentTimeMillis();
            ToastUtil.showToast("再按一次退出程序", Toast.LENGTH_LONG);
        } else {
            ((ApplicationShare) (getApplication())).getSdkAdapter().disconnect();
            AppManager.getAppManager().finishAllActivity();
            System.exit(0);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //在activity执行onDestroy时执行mMapView.onDestroy()，销毁地图
        mapView.onDestroy();
    }

    @Override
    protected void onResume() {
        super.onResume();
        //在activity执行onResume时执行mMapView.onResume ()，重新绘制加载地图
        mapView.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        //在activity执行onPause时执行mMapView.onPause ()，暂停地图的绘制
        mapView.onPause();
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        //在activity执行onSaveInstanceState时执行mMapView.onSaveInstanceState (outState)，保存地图当前的状态
        mapView.onSaveInstanceState(outState);
    }

}